<template>
  <div class="sign-management-page">
    <!-- 顶部培训班信息 -->
    <div class="top-info">
      <span>实践项目：{{practicalProjectName}}</span>
      <span>实践时间：{{practiceTime}}</span>
      <span>实践教师：{{practicalTeacherName}}</span>
      <span>地点：{{practiceAddress}}</span>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area" v-show="showSearch">
      <el-form inline :model="searchForm" class="search-form">
        <el-form-item label="姓名">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入姓名"
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input
            v-model="searchForm.phone"
            placeholder="请输入手机号码"
            class="search-input"
            maxlength="11"
          />
        </el-form-item>
        <el-form-item label="证件编号">
          <el-input
            v-model="searchForm.idCard"
            placeholder="请输入证件编号"
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="签到状态">
          <el-select
            v-model="searchForm.signStatus"
            placeholder="选择签到状态"
            class="search-select"
          >
            <el-option label="全部" value="" />
            <el-option label="已签到" value="1" />
            <el-option label="未签到" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-buttons">
      <el-button @click="handleExport" type="primary" plain style="margin-left: 4px;border: none;">导出</el-button>
      <el-button
        type="primary"
        plain style="margin-left: 4px;border: none;"
        @click="showNoticeDialog = true"
        :disabled="selectedRows.length === 0"
      >
       学员通知
      </el-button>
      <el-button
        type="primary"
        plain style="margin-left: 4px;border: none;"
        @click="handleBatchSetSign(true)"
        :disabled="selectedRows.length === 0"
      >设为已签到</el-button>
      <el-button
        type="primary"
        plain style="margin-left: 4px;border: none;"
        @click="handleBatchSetSign(false)"
        :disabled="selectedRows.length === 0"
      >设为未签到</el-button>
      <el-button @click="handleRemark" type="primary" plain style="margin-left: 4px;border: none;">备注</el-button>
      <el-button @click="showSearch = !showSearch" type="primary" plain style="margin-left: 4px;border: none;">
        {{ showSearch ? '隐藏搜索' : '显示搜索' }}
      </el-button>
      <el-button @click="handleRefresh" type="primary" plain style="margin-left: 4px;border: none;">刷新</el-button>
    </div>

    <!-- 签到结果表格 -->
    <el-table
      ref="signTable"
      :data="signList"
      border
      stripe
      size="mini"
      style="width: 100%; margin-bottom: 16px;"
      @selection-change="handleSelectionChange"
      v-loading="loading"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="name" label="姓名" width="100" align="center"></el-table-column>
      <el-table-column prop="idCard" label="证件编号" width="180" align="center"></el-table-column>
      <el-table-column prop="phone" label="电话" width="130" align="center"></el-table-column>
      <el-table-column label="签到状态" align="center" width="120">
        <template #default="scope">
          <span
            :class="scope.row.signStatus === '已签到' ? 'tag signed' : 'tag unsigned'"
          >
            {{ scope.row.signStatus }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" align="left" width="120"></el-table-column>

      <el-table-column prop="trainingProject" label="培训项目" width="150" align="center"></el-table-column>
      <el-table-column prop="trainingCode" label="培训班编号" width="120" align="center"></el-table-column>
      <el-table-column prop="trainingClass" label="培训班" width="100" align="center"></el-table-column>
      <el-table-column prop="headTeacher" label="班主任" width="150" align="center"></el-table-column>

      <el-table-column label="操作" align="center" width="120" fixed="right">
        <template #default="scope">
          <el-button
            type="text"
            @click="handleSingleSetSign(scope.row)"
            :loading="scope.row.btnLoading"
            v-if="scope.row.signStatus === '已签到'"
          >设为未签到</el-button>
          <el-button
            type="text"
            @click="handleSingleSetSign(scope.row)"
            :loading="scope.row.btnLoading"
            v-if="scope.row.signStatus === '未签到'"
          >设为已签到</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentPageChange"
      :current-page="pagination.currentPage"
      :page-sizes="[10, 20, 50]"
      :page-size="pagination.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
      size="mini"
      style="text-align: right; margin-top: 8px;"
    />

    <!-- 学员通知弹窗 -->
    <el-dialog
      title="发送学员通知"
      :visible.sync="showNoticeDialog"
      width="600px"
    >
      <el-form
        ref="noticeForm"
        :model="noticeForm"
        :rules="noticeRules"
        label-width="100px"
      >
        <el-form-item label="通知对象" disabled>
          <div class="recipient-list">
            <el-tag
              v-for="(row, index) in selectedRows"
              :key="row.practiceCheckId"
              closable
              @close="handleRemoveRecipient(index)"
              type="info"
            >
              {{ row.name }}（{{ row.phone }}）
            </el-tag>
            <div v-if="selectedRows.length === 0" class="empty-recipient">
              暂无通知对象，请先选择学员
            </div>
          </div>
        </el-form-item>

        <el-form-item label="通知类型" prop="noticeType">
          <el-radio-group v-model="noticeForm.noticeType">
            <el-radio label="sms">短信通知</el-radio>
            <el-radio label="system">站内通知</el-radio>
            <el-radio label="both">短信+站内通知</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="通知内容" prop="content">
          <el-input
            v-model="noticeForm.content"
            type="textarea"
            rows="5"
            placeholder="请输入通知内容（短信不超过70字）"
            @input="handleContentInput"
          />
          <div class="content-count">{{ noticeForm.content.length }}/70</div>
        </el-form-item>

        <el-form-item label="发送时间" prop="sendTime">
          <el-radio-group v-model="noticeForm.sendTime">
            <el-radio label="immediate">立即发送</el-radio>
            <el-radio label="timed">定时发送</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          label="定时时间"
          prop="timedSendTime"
          v-if="noticeForm.sendTime === 'timed'"
        >
          <el-date-picker
            v-model="noticeForm.timedSendTime"
            type="datetime"
            placeholder="选择发送时间"
            style="width: 100%;"
            :disabled-date="disabledDate"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="showNoticeDialog = false">取消</el-button>
        <el-button
          type="primary"
          @click="handleSendNotice"
          :disabled="selectedRows.length === 0"
        >
          确认发送
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { searchCheckIn, batchUpdateStatus } from "@/api/training/practiceCheckIn.js";
export default {
  name: "SignManagementPage",
  data() {
    return {
      // 搜索表单
      searchForm: {
        name: "",
        phone: "",
        idCard: "",
        signStatus: ""
      },
      // 控制搜索区域显隐
      showSearch: true,
      // 表格选中行
      selectedRows: [],
      // 签到数据列表（从接口获取）
      signList: [],
      // 分页配置
      pagination: {
        currentPage: 1,
        pageSize: 10
      },
      // 总数据量
      totalCount: 0,
      // 全局加载状态
      loading: false,
      // 学员通知相关
      showNoticeDialog: false,
      noticeForm: {
        noticeType: "sms",
        content: "",
        sendTime: "immediate",
        timedSendTime: ""
      },
      noticeRules: {
        noticeType: [
          { required: true, message: "请选择通知类型", trigger: "change" }
        ],
        content: [
          { required: true, message: "请输入通知内容", trigger: "blur" },
          { max: 70, message: "通知内容不能超过70个字", trigger: "input" }
        ],
        timedSendTime: [
          { required: true, message: "请选择定时发送时间", trigger: "change" }
        ]
      },

      //数据
      practicalProjectName:"",
      practiceTime:"",
      practicalTeacherName:"",
      practiceAddress:"",
      practiceAppointmentId:"",
    };
  },
  watch: {
    '$route.query.practiceAppointmentId': {
      immediate: true,
      handler(newId) {
        const params = this.$route.params;
        this.practiceAppointmentId = params.practiceAppointmentId
        this.practicalProjectName = params.practicalProjectName
        this.practiceTime = params.practiceTime
        this.practicalTeacherName = params.practicalTeacherName
        this.practiceAddress = params.practiceAddress
      }
    }
  },
  created() {
    this.getList();
  },
  methods: {
    async getList() {
      this.loading = true;
      try {
        const params = {
          studentName: this.searchForm.name || "",
          phoneNumber: this.searchForm.phone || "",
          idNumber: this.searchForm.idCard || "",
          checkStatus: this.searchForm.signStatus || "",
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize
        };

        const res = await searchCheckIn(params);
        if (res.code === 200) {
          // 关键：补充主键practiceCheckId映射（接口需要该字段作为参数）
          this.signList = res.rows.map(item => ({
            practiceCheckId: item.practiceCheckId || "", // 后端主键字段
            name: item.studentName || "",
            idCard: item.idNumber || "",
            phone: item.phoneNumber || "",
            signStatus: item.checkStatus || "", // 前端显示用（已签到/未签到）
            remark: item.remarks || "",
            trainingProject: item.projectName || "",
            trainingCode: item.trainingClassCode || "",
            trainingClass: item.trainingClassName || "",
            headTeacher: [item.head1TeacherName, item.head2TeacherName]
              .filter(Boolean)
              .join(" / ") || "无",
            btnLoading: false // 单个操作按钮的加载状态
          }));
          this.totalCount = res.total;
        } else {
          this.$message.error(res.msg || "获取数据失败");
          this.signList = [];
          this.totalCount = 0;
        }
      } catch (error) {
        console.error("请求失败:", error);
        this.$message.error("网络异常，获取数据失败");
        this.signList = [];
        this.totalCount = 0;
      } finally {
        this.loading = false;
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.currentPage = 1;
      this.getList();
    },

    // 重置搜索
    handleReset() {
      this.searchForm = {
        name: "",
        phone: "",
        idCard: "",
        signStatus: ""
      };
      this.pagination.currentPage = 1;
      this.getList();
      this.$message.info("搜索条件已重置");
    },

    // 表格选中行变化
    handleSelectionChange(val) {
      this.selectedRows = val;
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.getList();
    },

    // 分页页码改变
    handleCurrentPageChange(val) {
      this.pagination.currentPage = val;
      this.getList();
    },

    // 导出
    handleExport() {
      this.$message.info("导出功能待实现");
    },

    /**
     * 批量设置签到状态
     * @param {Boolean} isSigned - true=设为已签到，false=设为未签到
     */
    async handleBatchSetSign(isSigned) {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }

      // 1. 状态映射：前端文字 → 后端数值（0=未签到，1=已签到）
      const targetStatusText = isSigned ? "已签到" : "未签到";
      const targetStatus = isSigned ? "1" : "0"; // 后端需要字符串还是数字？按用户给的示例用字符串
      const originalStatusText = isSigned ? "未签到" : "已签到";

      // 2. 筛选需修改的行（避免重复调用接口）
      const needUpdateRows = this.selectedRows.filter(
        row => row.signStatus === originalStatusText && row.practiceCheckId
      );
      if (needUpdateRows.length === 0) {
        this.$message.info(`所选学员已全部为${targetStatusText}`);
        return;
      }

      // 3. 构造接口参数（主键数组+目标状态）
      const params = {
        practiceCheckIds: needUpdateRows.map(row => row.practiceCheckId), // 主键数组
        checkStatus: targetStatus // 目标状态值
      };

      // 4. 确认操作
      try {
        await this.$confirm(
          `是否将“${needUpdateRows.map(row => row.name).join("、")}”设为${targetStatusText}?`,
          "系统提示",
          { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" }
        );

        // 5. 调用接口（显示全局加载）
        this.loading = true;
        const res = await batchUpdateStatus(params);

        // 6. 接口成功处理
        if (res.code === 200) {
          this.$message.success(`已成功将${needUpdateRows.length}名学员设为${targetStatusText}`);
          this.$refs.signTable.clearSelection(); // 清空选中
          this.getList(); // 刷新列表获取最新状态
        } else {
          this.$message.error(`操作失败：${res.msg || "服务器异常"}`);
        }
      } catch (error) {
        // 7. 取消操作或接口失败处理
        if (error === "cancel") {
          this.$message.info(`已取消设为${targetStatusText}操作`);
        } else {
          console.error("批量修改状态失败:", error);
          this.$message.error("网络异常，操作失败，请重试");
        }
      } finally {
        this.loading = false;
      }
    },

    /**
     * 单个设置签到状态（复用batchUpdateStatus接口）
     * @param {Object} row - 表格当前行数据
     */
    async handleSingleSetSign(row) {
      // 1. 状态映射：根据当前状态确定目标状态
      const isCurrentSigned = row.signStatus === "已签到";
      const targetStatusText = isCurrentSigned ? "未签到" : "已签到";
      const targetStatus = isCurrentSigned ? "0" : "1"; // 0=未签到，1=已签到

      // 2. 构造接口参数（单个id的数组）
      console.log(row)
      let arr =[]
      arr.push(row.practiceCheckId)
      const params = {
        practiceCheckIds: arr, // 主键数组（单个元素）
        checkStatus: targetStatus
      };

      // 3. 确认操作
      try {
        await this.$confirm(
          `是否将“${row.name}”设为${targetStatusText}?`,
          "系统提示",
          { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" }
        );

        // 4. 显示按钮加载状态（避免重复点击）
        row.btnLoading = true;
        const res = await batchUpdateStatus(params);

        // 5. 接口成功处理
        if (res.code === 200) {
          this.$message.success(`已成功将“${row.name}”设为${targetStatusText}`);
          this.getList(); // 刷新列表
        } else {
          this.$message.error(`操作失败：${res.msg || "服务器异常"}`);
        }
      } catch (error) {
        // 6. 取消操作或接口失败处理
        if (error === "cancel") {
          this.$message.info(`已取消设为${targetStatusText}操作`);
        } else {
          console.error("单个修改状态失败:", error);
          this.$message.error("网络异常，操作失败，请重试");
        }
      } finally {
        // 7. 关闭按钮加载状态
        row.btnLoading = false;
      }
    },

    // 备注
    handleRemark() {
      this.$message.info("备注功能待实现");
    },

    // 刷新数据
    handleRefresh() {
      this.getList();
    },

    // 处理通知内容输入
    handleContentInput() {
      if (this.noticeForm.content.length > 70) {
        this.noticeForm.content = this.noticeForm.content.slice(0, 70);
      }
    },

    // 移除通知接收人
    handleRemoveRecipient(index) {
      this.selectedRows.splice(index, 1);
    },

    // 禁用过去的时间
    disabledDate(time) {
      return time.getTime() < Date.now() - 8.64e7;
    },

    // 发送通知
    handleSendNotice() {
      this.$refs.noticeForm.validate(valid => {
        if (valid) {
          this.$message.loading("正在发送通知...", 0);
          setTimeout(() => {
            const params = {
              recipients: this.selectedRows.map(row => ({
                id: row.practiceCheckId, // 用主键作为学员id
                phone: row.phone,
                name: row.name
              })),
              type: this.noticeForm.noticeType,
              content: this.noticeForm.content,
              sendTime: this.noticeForm.sendTime === "immediate"
                ? new Date().toISOString()
                : new Date(this.noticeForm.timedSendTime).toISOString()
            };
            console.log("发送通知参数：", params);
            this.$message.success(`成功发送通知给 ${this.selectedRows.length} 名学员`);
            this.showNoticeDialog = false;
            this.$refs.noticeForm.resetFields();
            this.$refs.signTable.clearSelection();
          }, 1500);
        }
      });
    }
  }
};
</script>

<style scoped>
/* 样式部分不变，省略重复代码 */
.sign-management-page {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
  box-sizing: border-box;
}

.top-info {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
  font-size: 14px;
  color: #333;
  flex-wrap: wrap;
}

.top-info span {
  padding: 4px 8px;
  border-radius: 4px;
}

.search-area {
  margin-bottom: 20px;
  padding: 16px;
  border-radius: 4px;
}

.search-form {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
}

.search-input, .search-select {
  width: 180px;
}

.operation-buttons {
  margin-bottom: 15px;
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.tag {
  padding: 2px 6px;
  border-radius: 3px;
  font-weight: 500;
}
.signed {
  color: #4CAF50;
  background-color: rgba(76, 175, 80, 0.1);
}
.unsigned {
  color: #F44336;
  background-color: rgba(244, 67, 54, 0.1);
}

.el-table {
  font-size: 13px;
}
.el-table th {
  background-color: #f5f7fa !important;
}
.el-button { padding: 6px 10px; }

.recipient-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  max-height: 120px;
  overflow-y: auto;
  padding: 4px;
}

.empty-recipient {
  color: #999;
  padding: 8px 0;
  font-size: 13px;
}

.content-count {
  text-align: right;
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .top-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  .search-input, .search-select {
    width: 100%;
  }
}
</style>
